<!--
 * @Author: ningjz
 * @Date: 2022-03-16 14:02:53
 * @Description: 商品价格对比
-->
<template>
  <com-box>
    <template v-slot>
      <div class="box">
        <div class="box-sel">
          <el-row class="sel-row" :gutter="20">
            <el-col class="row-col" :span="6">
              <div>
                <el-select v-model="plState.plData" @change="handPLchange">
                  <el-option
                    v-for="item in plState.plList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col class="row-col" :span="15">
              <div class="top-date">
                <div class="til">日期选择</div>
                <el-date-picker
                  clearable
                  v-model="dateStart"
                  :type="plState.dateType"
                  :format="plState.format"
                  :value-format="plState.valFormat"
                  :placeholder="plState.placeholder"
                />
                <div class="til">至</div>
                <el-date-picker
                  clearable
                  v-model="dateEnd"
                  :type="plState.dateType"
                  :format="plState.format"
                  :value-format="plState.valFormat"
                  :placeholder="plState.placeholder"
                />
              </div>
            </el-col>
            <el-col class="row-col" :span="3">
              <div class="top-btn">
                <button @click="queryData()">搜索</button>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="sel-row">
            <el-col class="row-col" :span="6">
              <div>
                <el-select v-model="dbState.dbData" @change="queryData('db')">
                  <el-option
                    v-for="item in dbState.dbList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col class="row-col" :span="10">
              <div class="btm-good">
                <el-input
                  ref="ref_gooods"
                  v-model="spState.goodsNameData"
                  @focus="handInputClick('goods')"
                >
                  <template #suffix>
                    <el-icon
                      @click="handInputClick('goods')"
                      class="el-input__icon"
                    >
                      <moreFilled />
                    </el-icon>
                  </template>
                </el-input>
              </div>
            </el-col>
            <el-col class="row-col" :span="8">
              <div class="btm-area">
                <div class="til">地区</div>
                <el-input
                  ref="ref_area"
                  v-model="dqState.adNameData"
                  @focus="handInputClick('area')"
                >
                  <template #suffix>
                    <el-icon
                      @click="handInputClick('area')"
                      class="el-input__icon"
                    >
                      <moreFilled />
                    </el-icon>
                  </template>
                </el-input>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="box-echart">
          <right-echart :params="paramsData.list"></right-echart>
        </div>
      </div>
    </template>
  </com-box>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, watch } from 'vue'
import httpRequest from '@/service'
import rightEchart from './rightEchart.vue'
import comBox from '@/components/comBox/comBox.vue'
import { getDefaultDate } from '@/utils/date'
import { MoreFilled } from '@element-plus/icons-vue'
interface IplStart {
  //频率
  plData: string
  plList: any
  dateType: string //时间框类型
  placeholder: string //时间框提示语
  format: string //时间框显示格式
  valFormat: string //时间框赋值格式
  getPlData: () => void
}
interface IdbState {
  //对比类型
  dbData: string
  dbList: any
  getDbData: () => void
}
interface IspState {
  //商品
  goodsNameData: string
  goodsData: any
  goodsList: any
  getSpData: (classId: string) => void
}
interface IdqState {
  //地区
  adNameData: string
  adData: any
  adList: any
  getDqData: (classId: string) => void
}
const ref_area = ref()
const ref_gooods = ref()
export default defineComponent({
  name: 'rightDb',
  components: {
    comBox,
    MoreFilled,
    rightEchart
  },
  props: {
    tableData: {
      type: Object,
      default: () => {
        return {
          doogs: [],
          area: []
        }
      }
    },
    classId: {
      type: String,
      default: ''
    }
  },
  setup(porps, { emit }) {
    let dateStart = ref('')
    let dateEnd = ref('')
    let echartInit = ref(0)
    let paramsData = reactive({
      list: {}
    })
    //频率
    const plState: IplStart = reactive({
      // 频率
      plData: '9',
      plList: [],
      dateType: 'date', //时间框类型
      placeholder: '请选择日', //时间框提示语
      format: 'YYYY-MM-DD', //时间框显示格式
      valFormat: 'YYYY-MM-DD', //时间框赋值格式
      //频率
      getPlData: () => {
        httpRequest
          .get({ url: 'M3P3SpdqDbPL' })
          .then((res) => {
            plState.plList = res.data
            plState.plData = res.data[0].value
            handPLchange(plState.plData)
            let [startDate, endDate] = getDefaultDate(15)
            dateStart.value = startDate
            dateEnd.value = endDate
          })
          .catch(() => {
            console.log('请求失败')
          })
      }
    })
    plState.getPlData()
    const handPLchange = (newVal: any) => {
      dateStart.value = ''
      dateEnd.value = ''
      switch (newVal) {
        case 'month':
          plState.dateType = 'month'
          plState.placeholder = '请选择月份'
          plState.format = 'YYYY-MM'
          plState.valFormat = 'YYYY-MM'
          break
        case 'week':
          plState.dateType = 'week'
          plState.placeholder = '请选择周'
          plState.format = '第ww周'
          plState.valFormat = ''
          break
        case '9':
          plState.dateType = 'date'
          plState.placeholder = '请选择日'
          plState.format = 'YYYY-MM-DD'
          plState.valFormat = 'YYYY-MM-DD'
          break
      }
    }
    //对比类型
    const dbState: IdbState = reactive({
      // 对比类型
      dbData: '1',
      dbList: [],
      //对比
      getDbData: () => {
        httpRequest
          .get({ url: 'M3P3SpdqDbType' })
          .then((res) => {
            dbState.dbList = res.data
            dbState.dbData = res.data[0].value
          })
          .catch(() => {
            console.log('请求失败')
          })
      }
    })
    dbState.getDbData()
    // 商品
    const spState: IspState = reactive({
      goodsNameData: '',
      goodsData: [],
      goodsList: [],
      getSpData: (classId) => {
        httpRequest
          .get({
            url: 'M3P3SpdqDbSp',
            params: {
              classId: classId === 'null' ? '' : classId,
              contrastType: dbState.dbData
            }
          })
          .then((res) => {
            /**
             * 之前的逻辑是 后台返回为true 的默认为选中
             * 现在是 根据对比类型判断 前几个为默认选中的
             */
            const resData = res.data
            spState.goodsData = []
            resData.forEach((item: any, index: number) => {
              if (dbState.dbData === '1') {
                if (index < 5) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              } else {
                if (index === 0) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              }
            })
            spState.goodsList = JSON.parse(JSON.stringify(resData))
            spState.goodsData = res.data.filter((i: any) => i.checked)
            spState.goodsNameData = spState.goodsData
              .map((l: any) => l.name)
              .join('、')
            echartInit.value += 1
          })
          .catch(() => {
            echartInit.value += 1
            console.log('请求失败')
          })
      }
    })
    // 地区
    const dqState: IdqState = reactive({
      adNameData: '',
      adData: [],
      adList: [],
      getDqData: (classId) => {
        httpRequest
          .get({
            url: 'M3P3SpdqDbDq',
            params: {
              classId: classId === 'null' ? '' : classId,
              contrastType: dbState.dbData
            }
          })
          .then((res) => {
            /**
             * 之前的逻辑是 后台返回为true 的默认为选中
             * 现在是 根据对比类型判断 前几个为默认选中的
             */
            const resData = res.data
            dqState.adData = []
            resData.forEach((item: any, index: number) => {
              if (dbState.dbData === '1') {
                if (index === 0) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              } else {
                if (index < 3) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              }
            })
            dqState.adList = JSON.parse(JSON.stringify(resData))
            dqState.adData = res.data.filter((i: any) => i.checked)
            dqState.adNameData = dqState.adData
              .map((l: any) => l.name)
              .join('、')
            echartInit.value += 1
          })
          .catch(() => {
            echartInit.value += 1
            console.log('请求失败')
          })
      }
    }) // 点击商品、地区 显示弹窗
    const handInputClick = (val: string) => {
      if (val === 'goods') {
        ref_gooods.value.blur()
      } else {
        ref_area.value.blur()
      }
      emit('handInputClick', {
        doogs: spState.goodsList,
        area: dqState.adList,
        type: dbState.dbData
      })
    }
    // 获取周
    const getWeek = (dt: any) => {
      let date = new Date(dt)
      let d1: any = new Date(dt)
      let d2: any = date
      let year = date.getFullYear()
      d2.setMonth(0)
      d2.setDate(1)
      let rq = d1 - d2
      let days = Math.ceil(rq / (24 * 60 * 60 * 1000))
      let week = Math.ceil((days + 7) / 7)
      return { year, week }
    }
    // 点击搜索
    const queryData = (val?: string): void | boolean => {
      if (val === 'db') {
        spState.getSpData(porps.classId)
        dqState.getDqData(porps.classId)
        return false
      }
      let params = {
        goodsId: spState.goodsData.map((i: any) => i.value).join(),
        adCode: dqState.adData.map((i: any) => i.value).join(),
        frequencyType: plState.plData,
        classId: porps.classId === 'null' ? '' : porps.classId,
        contrastType: dbState.dbData,
        startDate: dateStart.value,
        endDate: dateEnd.value
      }
      if (plState.dateType === 'week') {
        params.startDate =
          dateStart.value !== ''
            ? getWeek(dateStart.value).year +
              '--' +
              getWeek(dateStart.value).week
            : ''
        params.endDate =
          dateEnd.value !== ''
            ? getWeek(dateEnd.value).year + '--' + getWeek(dateEnd.value).week
            : ''
      }
      paramsData.list = params
      if (echartInit.value !== 0) {
        echartInit.value = 0
      }
    }
    watch(
      () => porps.tableData,
      (newVal) => {
        spState.goodsList = newVal.goods
        spState.goodsData = newVal.goods.filter((i: any) => i.checked)
        spState.goodsNameData = spState.goodsData
          .map((l: any) => l.name)
          .join('、')
        dqState.adList = newVal.area
        dqState.adData = newVal.area.filter((i: any) => i.checked)
        dqState.adNameData = dqState.adData.map((l: any) => l.name).join('、')
        queryData('')
      }
    )
    watch(
      () => echartInit.value,
      (newVal) => {
        if (newVal === 2) {
          queryData('')
        }
      }
    )
    watch(
      () => porps.classId,
      (newVal) => {
        spState.getSpData(newVal === 'null' ? '' : newVal)
        dqState.getDqData(newVal === 'null' ? '' : newVal)
      }
    )
    return {
      plState,
      dbState,
      spState,
      dqState,
      paramsData,
      dateStart,
      dateEnd,
      queryData,
      handInputClick,
      handPLchange,
      ref_area,
      ref_gooods
    }
  }
})
</script>
<style lang="less" scoped>
.box {
  height: 100%;
  width: 100%;
  padding: 20px 20px 0px 24px;
  display: flex;
  flex-direction: column;
  .box-sel {
    width: 100%;
    height: 100px;
    // outline: 1px solid #f0f;
    .row-col {
      margin: 8px 0px;
      .top-btn button {
        cursor: pointer;
        width: 95%;
        background: transparent;
        color: #fff;
        padding: 6px 18px;
        box-shadow: none;
        border: 1px solid #1961cb;
        border-radius: 16px;
      }
      .btm-area,
      .top-date {
        display: flex;
        align-items: baseline;
        .til {
          white-space: nowrap;
          text-align: right;
          color: rgba(255, 255, 255, 0.8);
          margin: 0px 5px;
        }
      }
      .btm-area,
      .btm-good {
        ::v-deep(.el-input__inner) {
          cursor: pointer;
        }
        .el-input__icon {
          cursor: pointer;
        }
      }
    }
  }
  .box-echart {
    height: calc(100% - 110px);
  }
}
// 下拉框 & 输入框
::v-deep(.el-input) {
  .el-input__inner {
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    &:focus {
      box-shadow: none !important;
    }
  }
}
</style>
